import re

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from itsdangerous import TimedJSONWebSignatureSerializer

from users.models import User


def get_user_by(conut):
    try:
        if re.match(r'^1[3-9]\d{9}$',conut):
            user = User.objects.get(mobile=conut)
        else:
            user = User.objects.get(username=conut)
    except Exception as e:
        return  None
    else:
        return user
class UsernameMobileAuthentication(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        user = get_user_by(username)
        if user and user.check_password(password):
            return user

